package com.nuance.assignment.fileInfo.client.view;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.nuance.assignment.fileInfo.client.util.FileInfoConstants;
import com.nuance.assignment.fileInfo.shared.FileDTO;
import com.nuance.assignment.fileInfo.shared.FileJavaScriptObject;
import com.nuance.assignment.fileInfo.shared.FilePageJavaScriptObject;
import com.nuance.assignment.fileInfo.shared.FilePageResponseJavaScriptObject;

/**
 * Async data provider for fetching data for cell table that shows file info
 * 
 * @author parag
 *
 */
public class FileInfoDataProvider extends AsyncDataProvider<FileDTO> {

	private final FileInfoConstants constants;
	private HasText hasText;
	
	public FileInfoDataProvider(FileInfoConstants constants) {
		this.constants = constants;
	}
	
	@Override
	protected void onRangeChanged(HasData<FileDTO> display) {
		try{
			if(null != hasText){
				RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET,createUrl(display));
				requestBuilder.sendRequest(null, new RequestCallback(){
					@Override
					public void onError(Request request, Throwable exception) {
						Window.alert(exception.getMessage());
					}
					
					@Override
					public void onResponseReceived(Request request,
							Response response) {
						FilePageResponseJavaScriptObject responseJSObject = JsonUtils.safeEval(response.getText());
						if(responseJSObject.isSuccess()){
							FilePageJavaScriptObject filePageJavaScripObject = responseJSObject.getPalyload();
							List<FileDTO> dtos = new ArrayList<FileDTO>();
							for(FileJavaScriptObject fileJSObject : filePageJavaScripObject.getContent()){
								dtos.add(fileJSObject.toDto());
							}
							updateRowCount(filePageJavaScripObject.getTotal(), true);
							updateRowData(filePageJavaScripObject.getStart(), dtos);
						}else{
							String combinedMessage = "";
							for(String message : responseJSObject.getMessages()){
								combinedMessage += message+"\n";
							}
							Window.alert(combinedMessage);
						}
					}
					
				});
			}
		} catch (RequestException exception) {
			Window.alert(exception.getMessage());
		}
	}
	
	/**
	 * Create url to fetch data along with sorting and pagination information
	 * 
	 * @param display
	 * @return
	 */
	private String createUrl(HasData<FileDTO> display){
		CellTable<FileDTO> cellTable = (CellTable<FileDTO>)display;
		boolean ascending = 0 == cellTable.getColumnSortList().size() ? true : cellTable.getColumnSortList().get(0).isAscending();
		String sort = 0 == cellTable.getColumnSortList().size() ? "" : cellTable.getColumnSortList().get(0).getColumn().getDataStoreName();
		return GWT.getHostPageBaseURL() + constants.fileInfoUrl() + URL.encodeQueryString(hasText.getText())
				+ "&sort="+sort+"&start="+cellTable.getPageStart()+"&size="+cellTable.getPageSize()+"&ascending="+ascending;
	}
	
	public void setHasText(HasText hasText) {
		this.hasText = hasText;
	}
}
